﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GN.Pay.Application.GatewayApp;
using GN.Pay.Utils;
using GN.Pay.TradeChannel.WeiXin;

namespace GN.Pay.GatewayWeb.Controllers.Notify
{
    /// <summary>
    /// 微信通知控制器
    /// </summary>
    public class WeiXinController : APayNotifyController
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="tradeNotifyAppService"></param>
        public WeiXinController(ITradeNotifyAppService tradeNotifyAppService)
            : base(tradeNotifyAppService)
        {
        }

        /// <summary>
        /// 
        /// </summary>
        protected override string ChannelId
        {
            get
            {
                return "WeiXin.QRCode";
            }
        }

        public override void OrderPay()
        {
            XmlPayNotify();
        }

        private string RequestString(HttpRequestBase request)
        {
            string message;
            using (var input = request.InputStream)
            {
                input.Position = 0;
                message = input.ReadStreamString();
            }
            return message;
        }

        protected override NotifyMessage GetPayNotifyMessage(HttpRequestBase request)
        {
            var msg = RequestString(request);
            var no = WeiXinServiceBase.GetPayOrderNo(msg);
            return new NotifyMessage(no, msg);
        }

        protected override NotifyMessage GetRefundNotifyMessage(HttpRequestBase request)
        {
            var msg = RequestString(request);
            var no = WeiXinServiceBase.GetRefundNo(msg);
            return new NotifyMessage(no, msg);
        }       

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override ActionResult OrderPayReturn()
        {
            var requestDictionary = PreParam.GetQueryDictionary(this.Request);
            string tradeNo;
            if (requestDictionary.TryGetValue("tradeNo", out tradeNo))
            {
                return this.ReturnWaitResult(tradeNo);
            }
            else
            {
                return this.ErrorView();
            }
        }

        public override ActionResult OrderPayWapReturn()
        {
            var requestDictionary = PreParam.GetQueryDictionary(this.Request);
            string tradeNo;
            if (requestDictionary.TryGetValue("tradeNo", out tradeNo))
            {
                return this.ReturnWapWaitResult(tradeNo);
            }
            else
            {
                return this.WapErrorView();
            }
        }

        public override void OrderRefund()
        {
            Response.Write("Error");
        }

        
    }
}